//
//  StatusPictureView.swift
//  weibo
//
//  Created by Qing on 2017/8/6.
//  Copyright © 2017年 成哥哥. All rights reserved.
//

import UIKit
import SDWebImage

/// Item的Size
fileprivate let StatusPictureItemMargin: CGFloat = 40

/// 每个item之间的间距
fileprivate let StatusPictureItemSegmentationLine: CGFloat = 8


/// 注册配图可重用Cell Id
private let StatusPictureCellId = "StatusPictureCellId"

/// 略缩图 视图
class StatusPictureView: UICollectionView {
    
    
    var viewModel: StatusViewModel? {
        
        didSet{
            // 自动计算大小
            sizeToFit()
            
            //每次有新图就更新数据源 - 避免略缩图item重用，图片不更新。
            reloadData()
        }
    }
    
    override func sizeThatFits(_ size: CGSize) -> CGSize {
        
        return calcViewSize()
    }

    //MARK: - 实例化
    init() {
        
        let layout = UICollectionViewFlowLayout()
        
        // 设置间距： 默认 itemSize是 48 * 48
        layout.minimumLineSpacing = StatusPictureItemSegmentationLine
        layout.minimumInteritemSpacing = StatusPictureItemSegmentationLine
        
        
        super.init(frame: CGRect.zero, collectionViewLayout: layout)
    
//        backgroundColor = UIColor.clear
        
        // 设置数据源 - 自己当自己的数据源
        dataSource = self
        
        //注册可重用Cell
        register(StatusPictureViewCell.self, forCellWithReuseIdentifier: StatusPictureCellId)

    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}


// MARK: - 实现数据源代理
extension StatusPictureView: UICollectionViewDataSource {

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return viewModel?.thumbnail_pic?.count ?? 0
        
        
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = dequeueReusableCell(withReuseIdentifier: StatusPictureCellId, for: indexPath) as! StatusPictureViewCell
        
        cell.backgroundColor  = UIColor.blue
        cell.iconURL = viewModel!.thumbnail_pic![indexPath.row]
        print(indexPath)
        
        
        return cell
    }
}


// MARK: - 计算略缩视图大小
extension StatusPictureView {
    
    /// 计算视图大小
    fileprivate func calcViewSize() -> CGSize {
        
        /// 每行的图片数量
        let rowCount: CGFloat = 3
        
        /// 最大的宽度,屏幕最大宽度减去两边的间宽度。
        let maxWidth: CGFloat = UIScreen.main.bounds.width - StatusCellMargin * 2
        
        /// 每个item大小。一层有3张图片，每张图片中间会间隔， 所以会减去两个间隔。
        let itemWidth: CGFloat = (maxWidth - StatusPictureItemSegmentationLine * 2) / rowCount
        
        /// 设置layout的itemSize
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        
//        4.获取图片数量
        let count = viewModel?.thumbnail_pic?.count
        
        if count == 0 {
            
            return CGSize.zero
        }
        
        //TODO: - 一张图片临时大小
        
        if count == 1 {
            
            let size = CGSize(width: StatusPictureItemMargin, height: StatusPictureItemMargin)
//            指定内部照片大小
            layout.itemSize = size
            
            return size
        }
    
        if count == 4 {
            
            let w = 2 * itemWidth + StatusPictureItemSegmentationLine
            
            return CGSize(width: w, height: w)
        }
        
        if count == nil {
            print("我是空，所以我返回zero")
            return CGSize.zero
        }
        
        /*
         2 3
         5 6
         7 8 9
        */
        print("图片数量是count：\(count!)")
        let row = CGFloat((count! - 1) / Int(rowCount) + 1)
        print("现在的图片层数row\(row)")
        let h = row * itemWidth + (row - 1) * StatusPictureItemSegmentationLine
        let w = rowCount * itemWidth + (rowCount - 1) * StatusPictureItemSegmentationLine
        
        return CGSize(width: w, height: h)
    }
}


//MARK: - 配图Cell
class StatusPictureViewCell: UICollectionViewCell {
    
     var iconURL: URL? {
        didSet {
            
            iconView.sd_setImage(with: iconURL,
                                 placeholderImage: UIImage(named: ""),
                                 options: [SDWebImageOptions.retryFailed,
                                           SDWebImageOptions.refreshCached
                ])
            
        }
    }
    
    
    //MARK: - 构造函数
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        setUI()
        
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
//MARK: - 加载控件
    func setUI() {
        
        //1.添加控件
        contentView.addSubview(iconView)
        
        //2.控件布局
        iconView.frame = bounds
    }

//MARK: - 懒加载控件
    fileprivate let iconView: UIImageView = UIImageView()

}

